//日期格式函数
export function dateFormat(str, typeVal) {
	let oDate = new Date(str);
	let oYear = oDate.getFullYear();
	let oMonth = oDate.getMonth() + 1;
	let oDay = oDate.getDate();
	let oHour = oDate.getHours();
	let oMin = oDate.getMinutes();
	let oSen = oDate.getSeconds();
	if (typeVal == 1) { //月-日
		return getzf(oMonth) + "-" + getzf(oDay);
	}
	if (typeVal == 2) { //时-分
		return getzf(oHour) + ":" + getzf(oMin);
	}
	return oYear + "-" + getzf(oMonth) + "-" + getzf(oDay) + " " + getzf(oHour) + ":" + getzf(oMin) + ":" + getzf(oSen);
};

//补0操作1
function getzf(num) {
	if (parseInt(num) < 10) {
		num = '0' + num;
	}
	return num;
};

//时间差
export function getTimeDifference(date2, type) {
	// console.log(date2);
	let date1 = new Date(); //开始时间
	let date3 = null;
	if (type) {
		date3 = date1.getTime() - date2; // 
	} else {
		date3 = date2 - date1.getTime(); //时间差的毫秒数
	}
	// console.log(date3);
	//计算出小时数 
	let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数 
	let hours = Math.floor(leave1 / (3600 * 1000));
	//计算相差分钟数 
	let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数 
	let minutes = Math.floor(leave2 / (60 * 1000));
	//计算相差秒数 
	let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数 
	let seconds = Math.round(leave3 / 1000);
	let Date_data = {
		hour: hours,
		minute: minutes,
		second: seconds,
	};
	return Date_data;
	// return " 相差 " + hours+"小时 "+minutes+" 分钟"+seconds+" 秒"
};

//获取节点信息
export function getdomInfo(node, that) {
	return new Promise((resolve, reject) => {
		try {
			// console.log(node,that);
			const query = uni.createSelectorQuery().in(that);
			that.$nextTick(function() {
				query.select(node).boundingClientRect(data => {
					resolve(data);
				}).exec();
			});
		} catch (e) {
			reject(e);
		}
	});
};

export function copyTxt(txt) { //传入要复制的内容
	txt += "";
	if (txt == "null" || txt == "undefined" || txt == "") {
		//toast("复制失败，内容为空");
		return;
	}
	// #ifdef APP-PLUS
	uni.setClipboardData({
		data: txt,
	});
	// #endif

	// #ifdef H5
	if (document.queryCommandSupported('copy')) {
		let textarea = document.createElement("textarea")
		textarea.value = txt
		textarea.readOnly = "readOnly"
		document.body.appendChild(textarea)
		textarea.select() // 选中文本内容
		textarea.setSelectionRange(0, txt.length)
		let result = document.execCommand("copy")
		textarea.remove()
		uni.showToast({
			title: "复制成功",
			icon: "none",
		})
	} else {
		uni.showToast({
			title: "您的浏览器不支持复制",
			icon: "none"
		})
	}

	// #endif  
};
// 清空剪切板
export function clearCopyTxt() {
	let txt = "";
	// #ifdef APP-PLUS
	uni.setClipboardData({
		data: txt,
	});
	uni.hideToast();
	// #endif

	// #ifdef H5
	if (document.queryCommandSupported('copy')) {
		let textarea = document.createElement("textarea")
		textarea.value = txt
		textarea.readOnly = "readOnly"
		document.body.appendChild(textarea)
		textarea.select() // 选中文本内容
		textarea.setSelectionRange(0, txt.length)
		let result = document.execCommand("copy")
		textarea.remove()
	} else {
		uni.showToast({
			title: "您的浏览器不支持读取剪切板",
			icon: "none"
		})
	}

	// #endif  
};


//身份证验证
export const checkIDCard = (idCard) => {
	// 15位和18位身份证号码的正则表达式
	const regex = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/;

	// 基本格式校验
	if (!regex.test(idCard)) {
		return false;
	}

	// 校验18位身份证的校验码
	if (idCard.length === 18) {
		const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
		const parityBits = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
		let sum = 0;

		for (let i = 0; i < 17; i++) {
			sum += parseInt(idCard.charAt(i)) * factors[i];
		}

		const mod = sum % 11;
		const expectedParityBit = parityBits[mod];
		const actualParityBit = idCard.charAt(17).toUpperCase();

		return expectedParityBit === actualParityBit;
	}

	// 15位身份证号码不验证校验码（15位无校验码）
	return true;
}


//关闭浏览器窗口
export function closeWindow() {
	// #ifdef APP-PLUS
	if (plus.os.name.toLowerCase() === 'android') {
		plus.runtime.quit();
	} else {
		const threadClass = plus.ios.importClass("NSThread");
		const mainThread = plus.ios.invoke(threadClass, "mainThread");
		plus.ios.invoke(mainThread, "exit");
		// ios11
		plus.ios.import("UIApplication").sharedApplication().performSelector("exit")
	}
	// #endif

	// #ifdef H5
	setTimeout(() => {
		let browser = navigator.userAgent.toLowerCase();
		if (browser.match(/Alipay/i) == "alipay") {
			console.log("支付宝app的浏览器");
			//这个可以关闭安卓系统的手机
			document.addEventListener("AlipayJSBridgeReady", function() {
					AlipayJSBridge.call("closeWindow");
				},
				false
			);
			//这个可以关闭ios系统的手机
			AlipayJSBridge.call('closeWebview'); //支付宝
		} else if (browser.match(/MicroMessenger/i) == "micromessenger") {
			//这个可以关闭安卓系统的手机
			document.addEventListener("WeixinJSBridgeReady", function() {
					WeixinJSBridge.call("closeWindow");
				},
				false
			);
			//这个可以关闭ios系统的手机
			WeixinJSBridge.call("closeWindow");
		} else {
			console.log("其它浏览器");
			window.opener = null; //如果没有这行和下面的一行则会出现上面的第二个询问框。
			window.open(' ', '_self', ' ');
			window.close()
		}
	}, 2000)
	// #endif
}
//方法：用来判断是否是微信内置的浏览器
export function isWechat() {
	return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}

//获取地址参数
export function getUrlCode(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
		.replace(/\+/g, '%20')) || null
}

//请求微信接口，用来获取code
export function getWeChatCode() {
	console.log('getWeChatCode---------------')
	let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址 
	let appid = 'wx5d0ce05809618c7e'

	//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
	window.location.href =
		"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
		appid +
		"&redirect_uri=" +
		local +
		"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
}

//请求支付宝接口，用来获取code
export function getAlipayCode() {
	let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址 
	let appid = '2021004115688244'
	//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
	window.location.href =
		"https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" +
		appid +
		"&scope=auth_base&redirect_uri=" +
		local;
}

//获取图片信息
export function getImageInfo(src) {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src: src,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};
//根据经纬度计算距离
export function distance(lat1, lng1, location) {
	if (!lat1 || !lng1) return 0
	if (!location) return 0
	location = JSON.parse(location)
	let lat2 = location.lat;
	let lng2 = location.lng;
	let rad1 = lat1 * Math.PI / 180.0;
	let rad2 = lat2 * Math.PI / 180.0;
	let a = rad1 - rad2;
	let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) *
		Math.cos(
			rad2) * Math.pow(
			Math.sin(b / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	s = s.toString();
	s = s.substring(0, s.indexOf('.') + 2);
	return s
}

// 分钟差
export function mindiff(day) {
	var newDate = new Date();
	let disparity = newDate.getTime() - Number(day);
	// 转为分钟数的时候，可能会出现精度丢失;你需要注意下
	let second = disparity / 1000;
	return second;
};

//format = 'yyyy-MM-dd hh:mm:ss'
export function dateFormatType(date, format) {
	if (date) {
		let map = new Map();
		map.set('M+', date.getMonth() + 1);
		map.set('d+', date.getDate());
		map.set('d+', date.getDate());
		map.set('h+', date.getHours());
		map.set('m+', date.getMinutes());
		map.set('s+', date.getSeconds());
		map.set('q+', Math.floor((date.getMonth() + 3) / 3));
		map.set('S', date.getMilliseconds());
		if (/(y+)/.test(format)) {
			format = format.replace(
				RegExp.$1,
				`${date.getFullYear()}`.substr(4 - RegExp.$1.length)
			);
		}
		for (let [key, value] of map) {
			if (new RegExp(`(${key})`).test(format)) {
				format = format.replace(
					RegExp.$1,
					RegExp.$1.length == 1 ?
					value :
					`00${value}`.substr(`${value}`.length)
				);
			}
		}
	}
	return format;
}


// 数字缩写转换
export function abbreviateNumber(num) {
	if (typeof Number(num) !== 'number') {
		return 0
	}

	// 处理负数
	const isNegative = num < 0;
	num = Math.abs(num);

	// 转换逻辑
	let result;
	if (num >= 10000) {
		// 大于等于 10000 转换为 "w" 单位
		result = (num / 10000).toFixed(2) + 'w';
	} else if (num >= 1000) {
		// 大于等于 1000 转换为 "k" 单位
		result = (num / 1000).toFixed(2) + 'k';
	} else {
		// 小于 1000 保持原样
		result = num.toString();
	}

	// 恢复负号
	return isNegative ? '-' + result : result;
}
// 获取最近15天
export function getLastFifteenDays(format = 'YYYY-MM-DD') {
	const dates = [];

	for (let i = 0; i < 15; i++) {
		const date = new Date();
		date.setDate(date.getDate() + i);

		// 格式化日期
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');

		// 根据格式字符串替换占位符
		const formattedDate = format
			.replace('YYYY', year)
			.replace('MM', month)
			.replace('DD', day);

		dates.push(formattedDate);
	}

	return dates;
}

// 根据日期生成小时列表
export function getDayHours(selectedDateString) {
	// 解析传入的日期字符串
	const selectedDate = new Date(selectedDateString);

	// 获取当前时间
	const now = new Date();

	// 比较日期（忽略时间部分）
	const isSameDay =
		selectedDate.getFullYear() === now.getFullYear() &&
		selectedDate.getMonth() === now.getMonth() &&
		selectedDate.getDate() === now.getDate();

	const hours = [];
	const startHour = isSameDay ? now.getHours() : 0;

	for (let hour = startHour; hour < 24; hour++) {
		const formattedHour = String(hour).padStart(2, '0');
		hours.push(`${formattedHour}:00`);
	}

	return hours;
}
//将图片转换为 Base64 编码
export function imageToBase64(source) {
	return new Promise((resolve, reject) => {
		// 处理 File 对象
		if (source instanceof File) {
			const reader = new FileReader();
			reader.onload = function() {
				resolve(reader.result);
			};
			reader.onerror = reject;
			reader.readAsDataURL(source);
			return;
		}

		// 处理图片 URL
		if (typeof source === 'string') {
			const img = new Image();
			img.crossOrigin = 'anonymous'; // 允许跨域加载
			img.onload = function() {
				const canvas = document.createElement('canvas');
				canvas.width = img.width;
				canvas.height = img.height;

				const ctx = canvas.getContext('2d');
				ctx.drawImage(img, 0, 0);

				// 将图片转换为 Base64
				const dataURL = canvas.toDataURL('image/png');
				resolve(dataURL);
			};
			img.onerror = reject;
			img.src = source;
			return;
		}

		reject(new Error('不支持的源类型，必须是 File 对象或图片 URL'));
	});
}

//将时间戳转换为指定格式的日期字符串
export function formatTimestamp(timestamp, format = 'YYYY-MM-DD') {
	const date = new Date(timestamp);

	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const hour = String(date.getHours()).padStart(2, '0');
	const minute = String(date.getMinutes()).padStart(2, '0');
	const second = String(date.getSeconds()).padStart(2, '0');

	return format
		.replace('YYYY', year)
		.replace('MM', month)
		.replace('DD', day)
		.replace('HH', hour)
		.replace('mm', minute)
		.replace('ss', second);
}
//将日期格式化为 DD/MM/YYYY 格式
export function formatDateToDDMMYYYY(date) {
	// 转换输入为 Date 对象
	const inputDate = new Date(date);

	// 验证日期有效性
	if (isNaN(inputDate.getTime())) {
		throw new Error('无效的日期');
	}

	// 获取日、月、年并格式化为两位数
	const day = String(inputDate.getDate()).padStart(2, '0');
	const month = String(inputDate.getMonth() + 1).padStart(2, '0');
	const year = inputDate.getFullYear();

	// 拼接成 DD/MM/YYYY 格式
	return `${day}/${month}/${year}`;
}